package com.cm.stock.manager.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;

import com.cm.stock.manager.dto.FamilleDTO;

@Transactional
public class FamilleDAO {
	@PersistenceContext
	private EntityManager em;
	
	public FamilleDTO get(Integer id){
		return em.find(FamilleDTO.class, id);
	}
	
	public FamilleDTO save(FamilleDTO fa){
		em.persist(fa);
		return fa;
	}
	
	public FamilleDTO update(FamilleDTO fa){
		return em.merge(fa);
	}
	
	public FamilleDTO getByCode(String code){
		try{
			return (FamilleDTO) em.createQuery("select f from FamilleDTO f where f.code=:code")
					.setParameter("code", code).getSingleResult();
		}catch (NoResultException e) {
			return null;
		}
		
	}
	
	@SuppressWarnings("unchecked")
	public List<FamilleDTO> getAll(){
		
		return em.createQuery("select f from FamilleDTO f").getResultList();
	}
	
public void deleteOne(Integer id) throws Exception {
		
		FamilleDTO famille = em.find(FamilleDTO.class, id);
		if(famille==null){
			throw new Exception("Famille inexistant!");
		}
		em.remove(famille);
	}

}
